package com.xixun.rainfall.ui;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.xixun.joey.uart.IUartService;
import com.xixun.rainfall.App;
import com.xixun.rainfall.R;
import com.xixun.rainfall.databinding.ActivityMainBinding;
import com.xixun.rainfall.tools.UartTool;

import org.jetbrains.annotations.NotNull;

public class MainActivity extends AppCompatActivity {

//    private String port = "/dev/ttyS3";          //Android9的485地址
    private String port = "/dev/ttyS8";          //Android11的485地址
    private ActivityMainBinding mainBinding;
    private IUartService uart;                    //串口服务接口
    private MainViewModel mainViewModel;

    public static void startMainActivity(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    private final Handler mHandler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(@NonNull @NotNull Message msg) {
            super.handleMessage(msg);
        }
    };

    public Handler getmHandler() {
        return mHandler;
    }

    ServiceConnection conn = new ServiceConnection() {          //服务连接
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            uart = IUartService.Stub.asInterface(iBinder);       //服务连接时，通过服务返回的IBinder对象获取服务暴露的接口
            Log.i("TAG", "================ onServiceConnected ====================");
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.i("TAG", "================== onServiceDisconnected ====================");
            uart = null;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        mainViewModel = new ViewModelProvider(this).get(MainViewModel.class);
        App.getApp().setMainViewModel(mainViewModel);
        initObserver();
        initUartService();
    }

    private void initObserver(){
        mainViewModel.getWaterLevelLiveData().observe(this, s -> {
            App.logD("水位："+s);
            mainBinding.tvNowWaterLevel.setText(getString(R.string.water_level,s));
        });

        mainViewModel.getHourlyRainfallLiveData().observe(this, s -> {
            App.logD("小时雨量："+s);
            mainBinding.tvHourlyRainfall.setText(getString(R.string.hourly_rainfall,s));
        });

        mainViewModel.getDailyRainfallLiveData().observe(this, s -> {
            App.logD("今日雨量："+s);
            mainBinding.tvDailyRainfall.setText(getString(R.string.daily_rainfall,s));
        });
    }

    /**
     * 读取串口数据
     */
    private void initUartService() {
        //客户端绑定服务
        Intent intent = new Intent("xixun.intent.action.UART_SERVICE");
        intent.setPackage("com.xixun.joey.cardsystem");
        bindService(intent, conn, Context.BIND_AUTO_CREATE);

        /***通过服务Aidl接口调用服务接口方法：读串口数据***/
        //串口数据读取处理子线程
        new Thread(() -> {
            //等待服务完成连接
            do {
                App.logD("等待aidl服务uart实例化....");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            } while (null == uart);
            App.logD("aidl服务uart实例化完成");

            //上述循环结构结束，表示aidl服务已连接上，可通过aidl接口进行本程序和cardsystem之间跨进程访问
            UartTool.receivePackage(port, uart);
        }).start();
    }
}